/**
 * @description 代码生成 API控制器
 * @author 韩
 */

const dayjs = require("dayjs");
const mode = require("../../model/development/codeGengeration.MODEL")
const { getFilter } = require("../../utils/setFilter");
const { randomUUID } = require("crypto");
const { createSearch, createColumns, createConfigIndex, createEditForm, createAction, createApi, createIndex } = require("./gengeration");
const { getSearchConfig, getColumnsConfig, saveFile, generationCode } = require("./util");
const path = require("path");
const fs = require("fs");
// 创建
const saveData = async ({
    id = undefined, title, modelData, remark, componentName, tableName
}) => {
    const params = {

        title, modelData, remark, componentName, tableName
    }
    let addRes = null;
    if (!id) {
        // 添加创建
        addRes = await mode.create({
            ...params,
            createDate: dayjs(),
            id: randomUUID(),
        })
    } else {
        // 更新修改
        addRes = await mode.findOneAndUpdate({ id: id }, {
            $set: {
                ...params
            }
        }, { new: true })
    }

    if (addRes) {
        const { id, title, modelData, createDate, remark, tableName } = addRes

        // deleteProductionImage({ imgList: discardImage })
        return {
            code: 0,
            msg: "成功",
            data: {
                id, title, modelData, createDate, remark, tableName
            }
        }
    }
    return {
        code: "2000",
        msg: "失败",
    }
}

// 查询列表 
const queryList = async ({ title, current, pageSize, }) => {
    try {
        let filter = {
            title: title && { $regex: eval("/" + title + "/i") },//商品名模糊查询
        }
        filter = getFilter(filter)
        const list = await mode.find(filter).sort({ createDate: -1 }).skip((current - 1) * pageSize).limit(pageSize).lean()
        const totalCount = await mode.find(filter).countDocuments()
        return {
            code: 0,
            msg: "查询成功",
            data: {
                list,
                totalCount
            }
        }
    } catch (error) {
        return {
            code: 12,
            msg: "查询失败"
        }
    }
}


const deepFindFile = (dirPath, object) => {

    const files = fs.readdirSync(dirPath);
    files.forEach((file) => {
        console.log("遍历到的文件：", file)
        const filePath = path.join(dirPath, file);
        const stat = fs.statSync(filePath);
        if (stat.isFile()) {
            const fileName = file.split(".")[0];
            object[fileName] = fs.readFileSync(filePath, "utf-8");
        } else {
            object[file] = {};
            deepFindFile(`${dirPath}/${file}`, object[file])
        }
    });
}

// 根据id查详情
const getDetail = async ({ id }) => {
    try {
        console.log("查看代码详情", id);
        const res = await mode.findOne({
            id
        })
        await generationCode({ id }, true)

        // 构建 temp 目录下的 src 子目录的路径
        const currentDir = __dirname;
        const dirPath = path.join(currentDir, '..', "..", 'template', 'src');
        let object = {};
        deepFindFile(dirPath, object)

        if (res) {
            const { id, title, modelData, createDate, remark, componentName, tableName } = res;
            return {
                code: 0,
                msg: "查询成功",
                data: {
                    id: id, title, modelData, createDate, remark, componentName, tableName,
                    object
                }
            }
        } else {
            return {
                code: '0001',
                msg: "详情获取失败"
            }
        }
    } catch (error) {
        console.log("程序报错了", error)
    }
}

// 删除
const deleteDocument = async ({ id = undefined, action = "clear" }) => {
    try {

        let res = null;
        if (action === "delete") {
            // 逻辑删除
            res = await mode.findOneAndUpdate({ id: id }, {
                $set: {
                    deleteFlag: true
                }
            }, { new: true })
        } else {
            //物理删除
            res = await mode.deleteOne({
                id: { $in: id }
            });
        }
        if (res) {
            return {
                code: 0,
                msg: `删除成功`
            }
        } else {
            return {
                code: 100,
                msg: `删除失败`
            }
        }
    } catch (error) {
        console.log("错误：", error)
    }
}






module.exports = {
    saveData, queryList, getDetail, deleteDocument
}